<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAdd">添加用户</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户表格 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="info" link @click="handleViewChildren(scope.row)">
              查看儿童
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 儿童管理对话框 -->
    <el-dialog
      v-model="childrenDialogVisible"
      :title="`${currentUser.username || ''} 的儿童管理`"
      width="800px"
    >
      <div class="children-dialog-header">
        <el-button type="primary" @click="handleAddChild">添加儿童</el-button>
      </div>

      <!-- 儿童列表 -->
      <el-table :data="childrenList" style="width: 100%" v-loading="childrenLoading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.gender }}
          </template>
        </el-table-column>
        <el-table-column prop="birthday" label="出生日期" width="180">
          <template #default="scope">
            {{ formatBirthday(scope.row.birthday) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="danger" link @click="handleDeleteChild(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 儿童表单对话框 -->
      <el-dialog
        v-model="childFormDialogVisible"
        title="添加儿童"
        width="500px"
        append-to-body
      >
        <el-form
          ref="childFormRef"
          :model="childForm"
          :rules="childRules"
          label-width="100px"
        >
          <el-form-item label="姓名" prop="name">
            <el-input v-model="childForm.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="childForm.gender">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker
              v-model="childForm.birthday"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="childFormDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleChildSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUserList, 
  getUserDetail, 
  addUser, 
  updateUser, 
  deleteUser, 
  updateUserStatus,
  getChildrenByUserId,
  getChildDetail,
  addChild,
  updateChild,
  deleteChild
} from '@/api/user'

// 搜索表单
const searchForm = reactive({
  username: '',
  phone: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const formRef = ref(null)
const form = reactive({
  id: null,
  username: '',
  password: '',
  nickname: '',
  phone: '',
  status: 1
})

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    console.log('请求参数:', params)
    const res = await getUserList(params)
    console.log('API响应:', res)
    
    // 直接使用返回的分页数据
    if (res && typeof res === 'object') {
      tableData.value = res.records || []
      total.value = res.total || 0
      currentPage.value = res.current || 1
      pageSize.value = res.size || 10
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error('获取用户列表失败')
      console.error('意外的响应格式:', res)
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    console.error('错误详情:', error.response || error)
    tableData.value = []
    total.value = 0
    ElMessage.error(error.response?.data?.message || '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

// 重置
const handleReset = () => {
  searchForm.username = ''
  searchForm.phone = ''
  searchForm.status = ''
  handleSearch()
}

// 添加用户
const handleAdd = () => {
  dialogType.value = 'add'
  form.id = null
  form.username = ''
  form.password = ''
  form.nickname = ''
  form.phone = ''
  form.status = 1
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  try {
    // 清空表单
    form.id = null
    form.username = ''
    form.password = ''
    form.nickname = ''
    form.phone = ''
    form.status = 1

    const res = await getUserDetail(row.id)
    console.log('获取用户详情响应:', res)
    
    if (res && typeof res === 'object') {
      // 如果响应直接就是数据对象
      if (res.id) {
        Object.assign(form, res)
      } 
      // 如果是标准响应格式
      else if (res.code === 0 && res.data) {
        Object.assign(form, res.data)
      } 
      else {
        throw new Error('获取用户数据失败')
      }
      
      // 清空密码字段，编辑时不显示密码
      form.password = ''
      dialogVisible.value = true
    } else {
      throw new Error('用户数据格式错误')
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
    console.error('错误详情:', error.response || error)
    ElMessage.error(error.message || '获取用户详情失败')
  }
}

// 切换用户状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  ElMessageBox.confirm(
    `确定要${row.status === 1 ? '禁用' : '启用'}该用户吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updateUserStatus(row.id, newStatus)
      ElMessage.success(`${row.status === 1 ? '禁用' : '启用'}成功`)
      row.status = newStatus
    } catch (error) {
      console.error('更新状态失败:', error)
      if (error.response?.data?.code === 41002) {
        ElMessage.error('账号已被禁用')
      } else {
        ElMessage.error('操作失败')
      }
    }
  })
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该用户吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      fetchUserList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addUser(form)
          ElMessage.success('添加成功')
        } else {
          await updateUser(form)
          ElMessage.success('编辑成功')
        }
        dialogVisible.value = false
        fetchUserList()
      } catch (error) {
        console.error('保存失败:', error)
        if (error.response?.data?.code === 41000) {
          ElMessage.error('用户名已存在')
        } else {
          ElMessage.error('保存失败')
        }
      }
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUserList()
}

// 儿童管理相关
const childrenDialogVisible = ref(false)
const childFormDialogVisible = ref(false)
const childDialogType = ref('add')
const childrenLoading = ref(false)
const childrenList = ref([])
const currentUser = ref({})
const childFormRef = ref(null)

const childForm = reactive({
  id: null,
  userId: null,
  name: '',
  gender: '男',
  birthday: ''
})

const childRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthday: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ]
}

// 查看用户的儿童列表
const handleViewChildren = async (row) => {
  currentUser.value = row
  childrenDialogVisible.value = true
  childrenLoading.value = true
  try {
    const res = await getChildrenByUserId(row.id)
    console.log('获取儿童列表响应:', res)
    
    // 处理响应数据
    if (res && typeof res === 'object') {
      // 如果响应直接就是数据数组
      if (Array.isArray(res)) {
        childrenList.value = res
      }
      // 如果响应是标准格式 {code: 0, data: [...]}
      else if (res.code === 0 && Array.isArray(res.data)) {
        childrenList.value = res.data
      }
      // 如果响应格式不正确
      else {
        console.error('意外的响应格式:', res)
        childrenList.value = []
        ElMessage.error('获取儿童列表失败')
      }
    } else {
      childrenList.value = []
      ElMessage.error('获取儿童列表失败')
    }
  } catch (error) {
    console.error('获取儿童列表失败:', error)
    console.error('错误详情:', error.response || error)
    childrenList.value = []
    ElMessage.error(error.response?.data?.message || '获取儿童列表失败')
  } finally {
    childrenLoading.value = false
  }
}

// 添加儿童
const handleAddChild = () => {
  childDialogType.value = 'add'
  childForm.id = null
  childForm.userId = currentUser.value.id
  childForm.name = ''
  childForm.gender = '男'
  childForm.birthday = ''
  childFormDialogVisible.value = true
}

// 删除儿童
const handleDeleteChild = (row) => {
  ElMessageBox.confirm(
    '确定要删除该儿童吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteChild(row.id)
      ElMessage.success('删除成功')
      // 重新获取儿童列表
      handleViewChildren(currentUser.value)
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 提交儿童表单
const handleChildSubmit = async () => {
  if (!childFormRef.value) return
  
  await childFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        childForm.userId = currentUser.value.id
        const res = await addChild(childForm)
        
        console.log('保存儿童信息响应:', res)
        
        if (res && res.code === 0) {
          ElMessage.success('添加成功')
          childFormDialogVisible.value = false
          // 重新获取儿童列表
          handleViewChildren(currentUser.value)
        } else {
          throw new Error(res?.message || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        console.error('错误详情:', error.response || error)
        ElMessage.error(error.message || '保存失败')
      }
    }
  })
}

// 日期格式化函数
const formatBirthday = (birthday) => {
  if (!birthday) return '';
  
  try {
    // 如果是日期格式字符串（如 YYYY-MM-DD），直接返回
    if (typeof birthday === 'string' && birthday.includes('-')) {
      return birthday;
    }
    
    // 将输入转换为数字
    const timestamp = Number(birthday);
    if (isNaN(timestamp)) {
      console.error('Invalid birthday format:', birthday);
      return '';
    }
    
    // 处理毫秒时间戳
    const date = new Date(String(timestamp).length === 10 ? timestamp * 1000 : timestamp);
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      console.error('Invalid date:', birthday);
      return '';
    }
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } catch (error) {
    console.error('Error formatting birthday:', error);
    return '';
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.children-dialog-header {
  margin-bottom: 20px;
}
</style> 